package daily;

import java.util.concurrent.TimeUnit;

/**
 * @Date 2024-02-23
 * @Author Jonathan
 */
public class PrintABC {
    private static volatile int COUNT = 0;
    private static Object lock = new Object();

    public static void main(String[] args) {

        Thread ta = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (COUNT % 3 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                        }
                    }
                    System.out.print("A");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                    }
                    COUNT++;
                    lock.notifyAll();
                }
            }
        }, "ta");


        Thread tb = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (COUNT % 3 != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                        }
                    }
                    System.out.print("B");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                    }
                    COUNT++;
                    lock.notifyAll();
                }
            }
        }, "tb");


        Thread tc = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (COUNT % 3 != 2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                        }
                    }
                    System.out.print("C");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                    }
                    COUNT++;
                    lock.notifyAll();
                }
            }
        }, "tc");


        ta.start();
        tb.start();
        tc.start();
    }
}
